package com.katesoft.scale4j.persistent.tools;

import java.util.concurrent.atomic.AtomicLong;

import org.hibernate.HibernateException;
import org.hibernate.envers.DefaultRevisionEntity;
import org.hibernate.event.SaveOrUpdateEvent;
import org.hibernate.event.SaveOrUpdateEventListener;

import com.katesoft.scale4j.log.LogFactory;
import com.katesoft.scale4j.log.Logger;
import com.katesoft.scale4j.persistent.model.unified.AbstractPersistentEntity;

/**
 * This is very simple in-memory unique id generator.
 * <p/>
 * this generator can't be used in clustered env, more over this class start counting from current
 * mili seconds, so you should not change system time (or at least do not decrease)
 * 
 * @author kate2007
 */
public class NotClusteredInMemoryIdentifierGeneratorListener implements SaveOrUpdateEventListener {
   private static final long serialVersionUID = 7286429820219013784L;
   private final AtomicLong atomicLong = new AtomicLong(System.currentTimeMillis());
   private final Logger logger = LogFactory.getLogger(getClass());

   @Override
   public void onSaveOrUpdate(SaveOrUpdateEvent event) throws HibernateException {
      if (event.getObject() instanceof AbstractPersistentEntity) {
         AbstractPersistentEntity entity = (AbstractPersistentEntity) event.getObject();
         if (entity.getUniqueIdentifier() == null) {
            long l = atomicLong.getAndIncrement();
            logger.debug("generated new unique_identifier %s for entity %s", l, event.getObject());
            entity.setUniqueIdentifier(l);
         }
      } else if (event.getObject() instanceof DefaultRevisionEntity) {
         DefaultRevisionEntity entity = (DefaultRevisionEntity) event.getObject();
         if (entity.getId() == 0) {
            long l = atomicLong.getAndIncrement();
            logger.debug("generated new unique_identifier %s for entity %s", (int) l,
                     event.getObject());
            entity.setId((int) l);
         }
      }
   }
}
